//
//  MainViewController.m
//  BuffetNews
//
//  Created by 李荃荃 on 14-10-27.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "MainViewController.h"
#import "FirstCollectionCell.h"
#import "AutoScrollView.h"
#import "NetHandler.h"
#import "WebColor.h"
#import "UIImageView+WebCache.h"
#import "WeatherViewController.h"
#import "SecondViewController.h"
#import "UIColor+imageColor.h"
#import "UIImage+Tint.h"
#import "CityWeather.h"
#import "WeiPlist.h"
#import "FindViewController.h"
#import "CommentViewController.h"
#import "TopicViewController.h"
#import "CDRTranslucentSideBar.h"
#import "NightModel.h"
#import "EnterTableViewCell.h"
#import "NightTableViewCell.h"
#import "ColorTableViewCell.h"
#import "FriendViewController.h"
#import "PersonViewController.h"
#import <ShareSDK/ShareSDK.h>
#import "DoneViewController.h"
#import "Reachability.h"
#import <SystemConfiguration/SystemConfiguration.h>
#import "MBProgressHUD.h"

@interface MainViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UIActionSheetDelegate, CDRTranslucentSideBarDelegate, UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain) NSMutableArray *bigArr;           //  用来存储rootBlocks.plist文件中读取的数组
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) UIScrollView *scrollerView;       //  屏幕上方滚动新闻
@property (nonatomic, retain) NSMutableArray *imageArr;         //  存储滚动新闻的图片的URL地址
@property (nonatomic, retain) AutoScrollView *autoScroll;       //  调用封装好的滚动相册
@property (nonatomic, assign) NSInteger tag;
@property (nonatomic, retain) NSMutableArray *fourImageArr;
@property (nonatomic, retain) UITableView *tableView;
//  左侧抽屉列表
@property (nonatomic, retain) CDRTranslucentSideBar *sideBar;
@property (nonatomic, retain) MBProgressHUD *mbP;

@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *img;

//  用来本地存储用户选择的城市，以便在用户下次进入程序的时候，直接获取该城市的天气
@property (nonatomic, retain) NSString *weatherString;
@end

@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        self.fourImageArr = [NSMutableArray array];
        NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
        //  消息中心1:监听城市选择，改变首页天气
        [notiCenter addObserver:self selector:@selector(weatherChange:) name:@"weather" object:nil];
        //  消息中心2:监听首页订阅的频道的改变（添加）
        [notiCenter addObserver:self selector:@selector(rootAdd:) name:@"rootAdd" object:nil];
        //  消息中心3：监听首页订阅的频道的改变（删除）
        [notiCenter addObserver:self selector:@selector(rootDelete:) name:@"rootDelete" object:nil];
        }
    return self;
}
//  消息中心1
- (void)weatherChange:(NSNotification *)niti
{
    
    CityWeather *city = niti.object;
    if (city.city != nil) {
        
        
        //  本地沙盒存储城市名称
    self.weatherString = city.city;//  存储选择的城市名
        NSString * str = city.city;
        NSLog(@"#####   %@", self.weatherString);
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentPath = [paths lastObject];
        NSString *strPath = [documentPath stringByAppendingPathComponent:@"/weather.txt"];
        BOOL result = [str writeToFile:strPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
        
        NSLog(@"天气写入本地结果：%d", result);
        
        
        
        
    //  一旦城市进行选择，首页导航栏右边
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 110, 30)];
    [button addTarget:self action:@selector(rightBarAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(50, 15, 50, 15)];
    name.userInteractionEnabled = YES;
    name.font = [UIFont systemFontOfSize:14];
    [button addSubview:name];
    name.text = city.city;
    name.textColor = [UIColor whiteColor];
    
    UILabel *temperature = [[UILabel alloc] initWithFrame:CGRectMake(50, 0, 80, 15)];
    temperature.font = [UIFont systemFontOfSize:14];
    [button addSubview:temperature];
    temperature.text = [NSString stringWithFormat:@"%@~%@℃", city.tmin, city.tmax];
    temperature.textColor = [UIColor whiteColor];
    temperature.userInteractionEnabled = YES;
    
    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 35, 30)];
    img.userInteractionEnabled = YES;
    [button addSubview:img];
    
    //  用来判断天气情况，改变首页显示的天气图片
    if ([city.weather_day isEqualToString:@"qing"]) {
        img.image = [UIImage imageNamed:@"iconfont-1qing.png"];
    } else if ([city.weather_day isEqualToString:@"duoyun"]) {
        img.image = [UIImage imageNamed:@"iconfont-duoyun.png"];
    } else if ([city.weather_day isEqualToString:@"zhenyu"]) {
        img.image = [UIImage imageNamed:@"iconfont-t04.png"];
    } else if ([city.weather_day isEqualToString:@"zhongyu"]) {
        img.image = [UIImage imageNamed:@"iconfont-t13.png"];
    } else if ([city.weather_day isEqualToString:@"yin"]) {
        img.image = [UIImage imageNamed:@"iconfont-t03.png"];
    } else if ([city.weather_day isEqualToString:@"xiaoyu"]) {
        img.image = [UIImage imageNamed:@"iconfont-4xiaoyu.png"];
    } else if ([city.weather_day isEqualToString:@"dayu"]) {
        img.image = [UIImage imageNamed:@"iconfont-t14.png"];
    } else if ([city.weather_day hasSuffix:@"xue"]) {
        img.image = [UIImage imageNamed:@"iconfont-xue.png"];
    }

    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    [name release];
    [img release];
    [temperature release];
    }
}

//  消息中心2:(添加频道)
- (void)rootAdd:(NSNotification *)noti
{
//  在用户从内容库中选择某一频道时，先判断这一频道是否存在在第一页面中，如果不存在，就在self.bigArr中添加字典
    NSString *pk = [noti.object objectForKey:@"pk"];
    BOOL result = NO;
    for (NSDictionary *dic in self.bigArr) {
        if ([pk isEqualToString:[dic objectForKey:@"pk"]]) {
            result = YES;
            break;  //  一旦找到相同元素则跳出循环
        } else {
            result = NO;
        }
    }


    if (result == NO) {
        
        [self.bigArr addObject:noti.object];
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        NSString *documentPath = [paths lastObject];
        
        NSString *filepath = [documentPath stringByAppendingPathComponent:@"rootBlocks.plist"];
        
        NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:self.bigArr, @"blocksData" ,nil];
        BOOL dicresult = [dic writeToFile:filepath atomically:YES];
        
        
        NSLog(@"writeResult : %d", dicresult);
    }
}

//  消息中心3:(删除频道)
- (void)rootDelete:(NSNotification *)noti
{
    //  在用户从内容库中删除某一频道时，先判断这一频道是否存在在第一页面中，如果存在，就在self.bigArr中删除字典元素
    NSString *pk = [noti.object objectForKey:@"pk"];
    
    for (NSDictionary *dic in self.bigArr) {
        if ([pk isEqualToString:[dic objectForKey:@"pk"]]) {
            
            [self.bigArr removeObject:dic];
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            
            NSString *documentPath = [paths lastObject];
            
            NSString *filepath = [documentPath stringByAppendingPathComponent:@"rootBlocks.plist"];
            
            NSDictionary * dic = [[NSDictionary alloc] initWithObjectsAndKeys:self.bigArr, @"blocksData" ,nil];
            BOOL dicresult = [dic writeToFile:filepath atomically:YES];
            NSLog(@"writeResult : %d", dicresult);
            break;  //  一旦找到相同元素则跳出循环
        }
    }

}

//  加载数据
- (void)dataConnect
{
    //  用来判断plist文件是否存在沙盒中，如果有，就从本地读取，如果没有就从工程中读取，并且拷贝一份文件到本地沙盒
    WeiPlist *plist = [[WeiPlist alloc] init];
    NSDictionary *rootDic = [plist dictionaryData:@"rootBlocks"];
    self.bigArr = [rootDic objectForKey:@"blocksData"];
    BOOL reachable = [[Reachability reachabilityForInternetConnection] isReachable];
    
    if (!reachable) {
        UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"请检查您的网络连接状态" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] autorelease];
        [alertView show];
        
    } else {
    
    //  滚动新闻接口
    NSString *stringImage = @"http://iphone.myzaker.com/zaker/follow_promote.php?_appid=AndroidPhone&_dev=18&_udid=864182029800498&_version=4.52&m=1414032616";
    
    //  网络请求数据
    [NetHandler networkWithURL:stringImage comaletion:^(id result) {
        self.fourImageArr = [[result objectForKey:@"data"] objectForKey:@"list"];
        //  滚动相册
        self.imageArr = [NSMutableArray array];
        self.titleName = [NSMutableArray array];
        
        
        for (int i = 0; i < [self.fourImageArr count]; i++) {
            NSString *imgUrl = [self.fourImageArr[i] objectForKey:@"promotion_img"];
            [self.imageArr addObject:imgUrl];
            //  AutoScrollView的 获取网络图片的方法
            
            NSString *titleName = [self.fourImageArr[i] objectForKey:@"title"]; //  将频道名字写入一个数组中
            [self.titleName addObject:titleName];
            [self.collectionView reloadData];
            self.autoScroll.titleArray = [NSMutableArray array];
            self.autoScroll.titleArray = self.titleName;
        }
        [self.autoScroll setImageUrls:self.imageArr];
    }];
    [plist release];
    }
}
-(BOOL)isReachableViaWWAN
{
    return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}
//  加载视图
- (void)loadingView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    //  flowLayout距离四周的距离在上面预留出一块位置，用来放滚动相册
    flowLayout.sectionInset = UIEdgeInsetsMake(201, 1, 1, 1);
    flowLayout.itemSize = CGSizeMake(105, 105);
    flowLayout.minimumLineSpacing = 1;       //  两行最小间距
    flowLayout.minimumInteritemSpacing = 1;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 100) collectionViewLayout:flowLayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsVerticalScrollIndicator = NO;

    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_collectionView];

    self.autoScroll = [[AutoScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
    //  设置滚动视图循环一次所用的时间
    self.autoScroll.timeInterval = 7;
    _autoScroll.backgroundColor = [UIColor whiteColor];
    [_collectionView addSubview:_autoScroll]; //  将滚动视图添加到collectionView上
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.autoScroll.scrollView addGestureRecognizer:tap];
    
    [tap release];
    [_autoScroll release];
    [_collectionView release];
    
    
    //  给collectionView注册一个cell
    [self.collectionView registerClass:[FirstCollectionCell class] forCellWithReuseIdentifier:@"Collecpool"];
    
    
    //  导航栏左侧推出列表抽屉
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"burger.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(leftBarAction:)];


    self.sideBar = [[CDRTranslucentSideBar alloc] init];
    self.sideBar.sideBarWidth = 200;
    self.sideBar.delegate = self;
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.sideBar setContentViewInSideBar:self.tableView];
    [_sideBar release];

    [flowLayout release];
    
    
    
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [paths lastObject];
    NSString *strPath = [documentPath stringByAppendingPathComponent:@"/weather.txt"];
    NSString *readStr = [[NSString alloc] initWithContentsOfFile:strPath encoding:NSUTF8StringEncoding error:nil];
    
    
    NSLog(@"readStr = %@", readStr);
    if (readStr == nil) {
        //  导航栏右键获取天气
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"获取天气"
                                                                                  style:UIBarButtonItemStyleBordered target:self action:@selector(rightBarAction:)];
        self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    } else {
        NSString *string = @"http://iphone.myzaker.com/zaker/get_weather.php?city=";
        NSString *netString = [string stringByAppendingString:readStr];
        [NetHandler networkWithURL:netString comaletion:^(id result) {
            
            //  数据解析，给Model类赋值
            NSDictionary *dic = [NSDictionary dictionary];
            dic = [[result objectForKey:@"data"] objectForKey:@"datas"];
            CityWeather *city = [[CityWeather alloc] init];
            city.city = [dic objectForKey:@"city"];
            city.treal = [dic objectForKey:@"treal"];
            city.weather_day = [dic objectForKey:@"weather_day"];
            city.weather_night = [dic objectForKey:@"weather-night"];
            city.tmax = [dic objectForKey:@"tmax"];
            city.tmin = [dic objectForKey:@"tmin"];
            
            
            NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
            [notiCenter postNotificationName:@"weather" object:city];
        }];
    }

    
    
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 30, 20)];
    titleLabel.text = @"订阅";
    titleLabel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = titleLabel;
    
    
    [self dataConnect];
    [self loadingView];
}

//  推出天气页面
- (void)rightBarAction:(UIBarButtonItem *)barButton
{
    WeatherViewController *weatherVC = [[WeatherViewController alloc] init];
    [self.navigationController pushViewController:weatherVC animated:YES];
    [weatherVC release];
}

//  导航栏左侧按钮实现的方法
- (void)leftBarAction:(UIBarButtonItem *)button
{
    [self.tableView reloadData];//  用来刷新tableView，主要是让清除缓存的cell上的文件个数刷新
    [self.sideBar show];
}

#pragma mark - tableView的协议实现方法

//   用来记录登录状态的全局变量，并且用来做判断
static int i = 0;

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 8;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool"];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"pool"] autorelease];
    }
    
    //  登录自定义cell
    EnterTableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:@"pool1"];
    
    //  夜间模式自定义cell
    NightTableViewCell *cell2 = [tableView dequeueReusableCellWithIdentifier:@"pool2"];
    
    //  更换主题自定义cell
    ColorTableViewCell *cell3 = [tableView dequeueReusableCellWithIdentifier:@"pool3"];
    
    
    if (indexPath.row == 0) {
        cell.textLabel.text = @"";
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    } else if (indexPath.row == 1) {
        if (cell1 == nil) {
            cell1 = [[[EnterTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"pool1"] autorelease];
        }
        
        if (i == 0) {
            
            cell1.enterLabel.text = @"新浪微博登录";
            cell1.imgView.image = [UIImage imageNamed:@"iconfont-ttpodicon.png"];
        } else {
            [cell1.imgView sd_setImageWithURL:[NSURL URLWithString:self.img]];
            cell1.enterLabel.text = self.name;
        }
        cell1.backgroundColor = [UIColor clearColor];
       
        return cell1;
    } else if (indexPath.row == 2) {
        if (cell2 == nil) {
            cell2 = [[[NightTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"pool2"] autorelease];
        }
        
        cell2.titleLabel.text = @"夜间模式";
        [cell2.switchButton addTarget:self action:@selector(switchButtonAction:) forControlEvents:UIControlEventValueChanged];
        cell2.backgroundColor = [UIColor clearColor];
        
        if ([NightModel shareInstance].open == 1) {
            cell2.switchButton.on = YES;
        } else {
            cell2.switchButton.on = NO;
        }
        return cell2;
    } else if (indexPath.row == 3) {
        //  清除缓存，并且显示catch文件里的文件个数
        cell.textLabel.text = @"清除缓存";
        NSString *string = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:string];
        
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%d个缓存文件", [files count]];
        
        cell.detailTextLabel.font = [UIFont systemFontOfSize:10];
        cell.tag = 10001;
        
    } else if (indexPath.row == 4) {
        if (cell3 == nil) {
            cell3 = [[[ColorTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"pool3"] autorelease];
        }
        
        cell3.title.text = @"BuffetNews主题";
        
        cell3.backgroundColor = [UIColor clearColor];
        cell3.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell3;
    }else if (indexPath.row == 5){
        if (cell == nil) {
            cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"pool"]autorelease];
        }
        cell.textLabel.text = @"关注的好友";
    }else if (indexPath.row == 6){
        if (cell == nil) {
            cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"pool"]autorelease];
        }
        cell.textLabel.text = @"关于我们";

    }else if (indexPath.row == 7){
        if (cell == nil) {
            cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"pool"]autorelease];
        }
        cell.textLabel.text = @"注销登录";
    }

    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

//  夜间模式开关
- (void)switchButtonAction:(UISwitch *)switchButton
{
    if (switchButton.on == YES) {
        [NightModel shareInstance].open = 1;
    } else {
        [NightModel shareInstance].open = 0;
    }
    
    //  消息中心，改变tabBar的模式（夜间模式）
    NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
    [notiCenter postNotificationName:@"Night" object:nil];
    [self.collectionView reloadData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 64;
    } else if (indexPath.row == 1) {
        return 80;
    } else if (indexPath.row == 4) {
        return 80;
    } else {
        return 60;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 1) {
        [ShareSDK getUserInfoWithType:ShareTypeSinaWeibo authOptions:nil result:^(BOOL result, id<ISSPlatformUser> userInfo, id<ICMErrorInfo> error) {
            if (result) {
                NSLog(@"新浪微博授权成功！");
                NSLog(@"uid:%@",[userInfo uid]);
                NSLog(@"nickname:%@",[userInfo nickname]);
                NSLog(@"profileImage:%@",[userInfo profileImage]);
                
                self.name = [userInfo nickname];
                self.img = [userInfo profileImage];
                
                
                UIAlertView* alverView = [[UIAlertView alloc]initWithTitle:nil message:@"授权成功" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil];
                [alverView show];
                i = 1;
                [self.tableView reloadData];
                
            }else{
                NSLog(@"新浪微博授权失败");
                NSLog(@"错误码:%d,错误描述:%@",[error errorCode],[error errorDescription]);
            }
        }];
    } else if (indexPath.row == 2) {
        
    } else if (indexPath.row == 3) {
        //  清除缓存
        dispatch_async(
                       dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                       , ^{
                           NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                           
                           NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];

                           for (NSString *p in files) {
                               NSError *error;
                               NSString *path = [cachPath stringByAppendingPathComponent:p];
                               if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                                   [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                               }
                           }
                           [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];});
    }else if (indexPath.row == 5){
        
        
        if (i == 0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"尚未登录" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
        } else {
        
        
        //  推出好友列表页面
        FriendViewController *friendTV = [[FriendViewController alloc]init];
        [friendTV setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
        [self presentViewController:friendTV animated:YES completion:^{
        }];
        [friendTV release];
        }
    }
    else if (indexPath.row == 6){
        //  推出个人中心界面
        PersonViewController *personVC = [[PersonViewController alloc] init];
        [personVC setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
        [self presentViewController:personVC animated:YES completion:^{
            
        }];
        
    }else if (indexPath.row == 7){
        if (i == 0) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Title" message:@"尚未登录" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
        } else {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Title" message:@"注销成功" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
            [ShareSDK cancelAuthWithType:ShareTypeSinaWeibo];//  注销登录
            i = 0;
        }
    }
    [self.tableView reloadData];
}

-(void)clearCacheSuccess
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Title" message:@"缓存清理完成！！" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alertView show];
    [alertView release];
    
    UITableViewCell *cell = (UITableViewCell *)[self.tableView viewWithTag:10001];
    cell.detailTextLabel.text = @"0个缓存文件";
}



#pragma mark - collectionView的协议方法的实现
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [self.bigArr count] + 1;//  cell的个数应该是所有的频道数加上最后一个添加cell
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    FirstCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Collecpool" forIndexPath:indexPath];
    if (indexPath.item < [self.bigArr count]) {
        NSString *imgUrl = [self.bigArr[indexPath.item] objectForKey:@"pic"];
        //  获取网络图片
        [cell.myImage sd_setImageWithURL:[NSURL URLWithString:imgUrl]completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            //  颜色反向渲染
            NSString *color = [self.bigArr[indexPath.item] objectForKey:@"block_color"];
            NSString *colorStr = [color substringFromIndex:1];
            cell.myImage.image = [cell.myImage.image imageWithTintColor:[UIColor colorWithHexString:colorStr]];
            
        }];
        cell.title.text = [self.bigArr[indexPath.item] objectForKey:@"block_title"];
    } else {
        //  添加最后一个添加cell
        cell.myImage.image = [UIImage imageNamed:@"iconfont-add.png"];
        cell.title.text = @"";
        
    }
    //  让cell实现方法（longPressAction:）
    cell.target = self;
    cell.action = @selector(longPressAction:);
    
    cell.tag = indexPath.row + 1000;                  //  给cell设置tag值，用于下面调用，用来取数组中相对应的元素

    
    if ([NightModel shareInstance].open == 1) {
        cell.backgroundColor = [WebColor dimGray];
        self.collectionView.backgroundColor = [UIColor grayColor];
        cell.title.textColor = [WebColor silver];
    } else {
        cell.backgroundColor = [WebColor whiteSmoke];
        self.collectionView.backgroundColor = [UIColor whiteColor];
        cell.title.textColor = [UIColor blackColor];
    }
    
    return cell;
}

//  长按方法的实现
- (void)longPressAction:(FirstCollectionCell *)cell
{
    self.tag = cell.tag;
    NSString *string = [NSString stringWithFormat:@"确定要删除 %@ 频道吗？", cell.title.text];
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:string delegate:self cancelButtonTitle:@"Cancle" destructiveButtonTitle:@"确定删除" otherButtonTitles:nil, nil];
    actionSheet.destructiveButtonIndex = 1;
    actionSheet.tag = 111;
    [actionSheet showInView:self.view];
    [actionSheet release];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        //  当选择删除按键的时候，响应删除频道的消息中心
        NSDictionary *dic = [self.bigArr objectAtIndex:self.tag - 1000];
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center postNotificationName:@"rootDelete" object:dic];
        [self.collectionView reloadData];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.item < [self.bigArr count]) {
        self.mbP = [[MBProgressHUD alloc] initWithView:self.view];
        [self.mbP setMode:MBProgressHUDModeIndeterminate];
        
        [self.mbP show:YES];
        [self.view addSubview:self.mbP];
        [self.mbP release];

        
        //  选择频道 跳转到二级页面（频道详情页面），通过将对应的api传到下一页
        NSString *str = [self.bigArr[indexPath.item] objectForKey:@"api_url"];
        
         [NetHandler networkWithURL:str comaletion:^(id result) {
             if ([[result objectForKey:@"msg"] isEqualToString:@"ok"]) {
                 [self.mbP removeFromSuperview];
                 SecondViewController *secondVC = [[SecondViewController alloc] init];
                 secondVC.apiString = str;
                 
                 //        [self.navigationController pushViewController:secondVC animated:YES];
                 NSLog(@"apiString == %@", secondVC.apiString);
                 
                 
                 
                 [secondVC setModalTransitionStyle:UINavigationControllerHideShowBarDuration];
                 [self presentViewController:secondVC animated:YES completion:^{
                     
                 }];
                 [secondVC release];
             } else {
                 DoneViewController *doneVC = [[DoneViewController alloc] init];
                 [self.navigationController pushViewController:doneVC animated:YES];
                 [doneVC release];
             }
         }];
        
        
        
    } else {
        
        //  如果点击最后添加cell，跳转到内容库页面
        FindViewController *findVC = [[FindViewController alloc] init];
        [self.navigationController pushViewController:findVC animated:YES];
        
        [findVC release];
    }
}

- (void)tapAction:(UITapGestureRecognizer *)tap
{
    
    BOOL reachable = [[Reachability reachabilityForInternetConnection] isReachable];
    
    if (!reachable) {
        UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"该功能需要连接网络才能使用，请检查您的网络连接状态" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] autorelease];
        [alertView show];
        
    } else {

    
    NSInteger pageNo = [self.autoScroll pageNo];
    NSDictionary *dic = self.fourImageArr[pageNo];
    NSString *type = [dic objectForKey:@"type"];
    if ([type isEqualToString:@"a"]) {
        //  根据type判断应该推出哪个页面，如果是“a”，则推出三级页面（webView）
        NSString *str = [[dic objectForKey:@"article"] objectForKey:@"weburl"];
        CommentViewController *commentVC = [[CommentViewController alloc] init];
        commentVC.webString = str;
        [self presentViewController:commentVC animated:YES completion:^{
            
        }];
    } else if ([type isEqualToString:@"block"]) {
        //  根据type判断应该推出哪个页面，如果是“block”，则推出频道页面
        NSString *str = [[dic objectForKey:@"block_info"] objectForKey:@"api_url"];
        SecondViewController *secondVC = [[SecondViewController alloc] init];
        secondVC.apiString = str;
        [secondVC setModalTransitionStyle:UINavigationControllerHideShowBarDuration];
        [self presentViewController:secondVC animated:YES completion:^{
            
        }];
    } else if ([type isEqualToString:@"topic"]) {
         //  根据type判断应该推出哪个页面，如果是“topic”，则推出专题页面
        TopicViewController *topicVC = [[TopicViewController alloc] init];
        topicVC.receiveDic = dic;//  属性传值，将点击的新闻对应的大字典传到下一页面中；
        [self presentViewController:topicVC animated:YES completion:^{
            
        }];
    } else if ([type isEqualToString:@"web"]) {
        NSString *str = [[dic objectForKey:@"web"] objectForKey:@"url"];
        CommentViewController *commentVC = [[CommentViewController alloc] init];
        commentVC.webString = str;
        [self presentViewController:commentVC animated:YES completion:^{
            
        }];

    }
    }
}


- (void)viewWillAppear:(BOOL)animated
{
    [self.mbP removeFromSuperview];
}
- (void)viewDidAppear:(BOOL)animated
{
    //  在页面出现的时候将导航栏显示出来，并且刷新collectionView
    self.navigationController.navigationBarHidden = NO;
    [self.collectionView reloadData];
    [self.tableView reloadData];
}


- (void)dealloc
{
    [_bigArr release];
    [_collectionView release];
    [_scrollerView release];
    [_imageArr release];
    [_autoScroll release];
    [_titleName release];
    [_fourImageArr release];
    [_sideBar release];
    [_weatherString release];
    [super dealloc];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
